const crypto = require('crypto')
const Runtime = require('../runtime/index')
const Modules = require('../modules')
const SessionStore = Runtime.SessionStore
const caasConfig = Runtime.App.AppConfig.runtime.caas
const log = Runtime.App.Log.helper

function md5Code() {
	let args = Array.prototype.slice.call(arguments, 0)
	let source = ''
	args.forEach(item => {
		source += item
	})
	source = source + caasConfig.md5
	const hash = crypto.createHash('md5')
	// 可任意多次调用update():
	hash.update(source)
	return hash.digest('hex') 
}

module.exports = {
	/**
	 * 根据AuthCode获取CAAS AccessToken以及UserInfo信息
	 */
	'/api/caas/auth': {
		method: 'get',
		validate: [{
			field: 'code',
			options: {
				required: true,
				missingMessage: 'code参数丢失'
			}
		}, {
			field: 'sign',
			options: {
				required: true,
				missingMessage: 'sign参数丢失'
			}
		}],
		callback: function(req, res, callback) {
			let code = req.query.code
			let sign = req.query.sign
			let actionResult = {
				success: false,
				code: -1,
				msg: 'error'
			}
			//Authcode本地验证
			if (sign !== md5Code(code)) {
				actionResult.success = false
				actionResult.code = -1
				actionResult.msg = '数据验证失败'
				callback(actionResult)
			} else {
				//callback({success:true,data:{code:code,sign:sign}})
				//return
				// 获取Token
				Modules.caas.doAuthAsync(code)
					.then(result => {
						if (result.success) {
							actionResult.success = true
							actionResult.code = 0

							// 根据Token获取用户信息
							Modules.caas.getUserInfoAsync(result.access_token)
								.then((userInfo) => {
									if (userInfo.success) {
										actionResult.data = {
											accessToken: result.access_token,
											expiresIn: result.expires_in,
											refreshToken: result.refresh_token,
											userCode: userInfo.user_code,
											userName: userInfo.user_name,
											sessionId: req.sessionID
										}
									} else {
										log.warning(userInfo.errorMessage || '')
										actionResult.success = false
										actionResult.msg = userInfo.errorMessage
									}
									console.log(actionResult)
									callback(actionResult)
								})
								.catch(ex => {
									log.error(ex)
									actionResult.success = false
									actionResult.msg = ex
									callback(actionResult)
								})

						} else {
							actionResult = result
							callback(actionResult)
						}
					})
					.catch(ex => {
						actionResult.success = false
						actionResult.code = -1
						actionResult.msg = ex
						log.error(ex)
						callback(actionResult)
					})
			}
		}
	},
	/**
	 * 根据用户Token获取CAAS 访问资源信息
	 */
	'/api/caas/resources': {
		method: 'get',
		validate: [{
				field: 'sessionId',
				options: {
					required: true,
					missingMessage: 'sessionId参数丢失'
				}
			},
			{
				field: 'token',
				options: {
					required: true,
					missingMessage: 'token参数丢失'
				}
			}, {
				field: 'sign',
				options: {
					required: true,
					missingMessage: 'sign参数丢失'
				}
			}
		],
		callback: function(req, res, callback) {
			let sessionId = req.query.sessionId
			let token = req.query.token
			let sign = req.query.sign
			let actionResult = {
				success: false,
				code: -1,
				msg: 'error'
			}
			// Authcode 本地验证
			if (sign !== md5Code(sessionId, token)) {
				actionResult.success = false
				actionResult.code = -1
				actionResult.msg = '数据验证失败'
				callback(actionResult)
			} else {
				// 获取Token
				Modules.caas.getUserPermissionAsync(token)
					.then(result => {
						if (result.success) {
							actionResult.success = true
							actionResult.code = 0
							actionResult.data = result.resource_codes
							console.log(result)
							callback(actionResult)
						} else {
							actionResult = result
							callback(actionResult)
						}
					})
					.catch(ex => {
						actionResult.success = false
						actionResult.code = -1
						actionResult.msg = ex
						log.error(ex)
						callback(actionResult)
					})
			}

		}
	},
	/**
	 * 根据用户Token获取所有的用户列表信息
	 */
	'/api/caas/userlist': {
		method: 'get',
		validate: [{
			field: 'sessionId',
			options: {
				required: true,
				missingMessage: 'sessionId参数丢失'
			}
		}, {
			field: 'sign',
			options: {
				required: true,
				missingMessage: 'sign参数丢失'
			}
		}],
		callback: function(req, res, callback) {
			let sessionId = req.query.sessionId
			let token = req.query.token
			let sign = req.query.sign
			let actionResult = {
				success: false,
				code: -1,
				msg: 'error'
			}
			// Authcode 本地验证
			if (sign !== md5Code(sessionId, token)) {
				actionResult.success = false
				actionResult.code = -1
				actionResult.msg = '数据验证失败'
				callback(actionResult)
			} else {
				// 获取Token
				SessionStore.getSessionAsync(sessionId)
					.then((session) => {
						if (session) {
							Modules.caas.getUserListAsync()
								.then(result => {
									if (result.success) {
										actionResult.success = true
										actionResult.code = 0
										actionResult.data = result.records || []
										console.log(result)
										callback(actionResult)
									} else {
										actionResult = result
										callback(actionResult)
									}
								})
								.catch(ex => {
									actionResult.success = false
									actionResult.code = -1
									actionResult.msg = ex
									log.error(ex)
									callback(actionResult)
								})
						} else {
							actionResult.success = false
							actionResult.code = -1
							actionResult.msg = "SessionExpires"
							callback(actionResult)
						}
					})
			}

		}
	},
	'/api/caas/refresh': {
		method: 'get',
		validate: [{
			field: 'token',
			options: {
				required: true,
				missingMessage: 'token参数丢失'
			}
		}, {
			field: 'sign',
			options: {
				required: true,
				missingMessage: 'sign参数丢失'
			}
		}],
		callback: function(req, res, callback) {
			let token = req.query.token
			let sign = req.query.sign
			let actionResult = {
				success: false,
				code: -1,
				msg: 'error'
			}
			//Authcode本地验证
			if (sign !== md5Code(token)) {
				actionResult.success = false
				actionResult.code = -1
				actionResult.msg = '数据验证失败'
				callback(actionResult)
			} else {
				// 获取Token
				let accessInfo = SessionStore.getAccessInfo(req)
				if (accessInfo && accessInfo.accessToken) {
					Modules.caas.refreshAuthAsync(accessInfo.refreshToken)
						.then(result => {
							if (result.success) {
								actionResult.success = true
								actionResult.code = 0
								//TODO ...
							} else {
								actionResult = result
								callback(actionResult)
							}
						})
						.catch(ex => {
							actionResult.success = false
							actionResult.code = -1
							actionResult.msg = ex
							log.error(ex)
							callback(actionResult)
						})

				}
			}
		}
	},
	'/api/caas/session': {
		method: 'get',
		validate: [{
			field: 'sid',
			options: {
				required: true,
				missingMessage: 'sid参数丢失'
			}
		}, {
			field: 'sign',
			options: {
				required: true,
				missingMessage: 'sign参数丢失'
			}
		}],
		callback: function(req, res, callback) {
			let sid = req.query.sid
			let sign = req.query.sign
			let actionResult = {
				success: false,
				code: -1,
				msg: '数据校验失败'
			}
			if (sign !== md5(sid)) {
				callback(actionResult)
			} else {
				SessionStore.getSessionAsync(sid)
					.then(session => {
						if (session) {
							actionResult.success = true
							actionResult.code = 0
							actionResult.msg = 'Session有效'
							callback(actionResult)
						} else {
							actionResult.msg = "Session已过期"
							callback(actionResult)
						}
					})
					.catch(ex => {
						actionResult.msg = ex
						callback(actionResult)
					})
			}
		}
	},
	'/api/caas/md5': {
		method: 'get',
		validate: [{
			field: 'code',
			options: {
				required: true,
				missingMessage: 'code参数丢失'
			}
		}],
		callback: function(req, res, callback) {
			callback({
				success: true,
				sign: md5Code(req.query.code)
			})
		}
	}
}